const Service = require('egg').Service;
const NodeRSA = require('node-rsa');
const crypto = require('crypto');

const fs = require('fs')
class RSAService extends Service {

    /**
     * @param 生成密钥对
     * @return boolean
     */
    async genNodeRSA() {
        const { config } = this;
        var key = new NodeRSA({ b: 512 })
        key.setOptions({ encryptionScheme: 'pkcs1' })
        var privatePem = key.exportKey('pkcs1-private-pem')
        var publicPem = key.exportKey('pkcs1-public-pem')
        fs.writeFileSync(config.baseDir + 'app/public/pem/public.pem', publicPem);
        fs.writeFileSync(config.baseDir + 'app/public/pem/private.pem', privatePem);
    }

    /**
     * @param 读取密钥对
     * @return boolean
     */
    async getNodeRSA() {
        const { config } = this;
        var publicPem = fs.readFileSync(config.baseDir + 'app/public/pem/public.pem');
        var privatePem = fs.readFileSync(config.baseDir + 'app/public/pem/private.pem');
        //转换成字符串
        publicPem = publicPem.toString();
        privatePem = privatePem.toString();
        return {
            publicPem,
            privatePem
        }
    }

    /**
     * 私钥，解密
     */
    async decrypt(data) {
        const { config } = this;
        var privatePem = fs.readFileSync(config.baseDir + 'app/public/pem/private.pem');
        var privateKey = privatePem.toString();
        let decodeData= crypto.privateDecrypt(privateKey, Buffer.from(data.toString('base64'), 'base64'));
        return decodeData.toString();
    }

    /**
     * 公钥，加密
     */
    async encrypt(data) {
        const { config } = this;
        var publicPem = fs.readFileSync(config.baseDir + 'app/public/pem/public.pem');
        var publicKey = publicPem.toString();
        return crypto.publicEncrypt(publicKey, Buffer.from(data)).toString('base64');
    }


}

module.exports = RSAService;